<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="任务名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="jobName">
              <a-input v-model="model.jobName" placeholder="请输入任务名称"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="提交模式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deployMode">
              <a-select placeholder="请输入提交模式:" v-model="model.deployMode" >
                <a-select-option value="LOCAL" >Local Cluster</a-select-option>
                <a-select-option value="STANDALONE" >Standalone Cluster</a-select-option>
                <a-select-option value="YARN_PER" >YARN PER</a-select-option>
                <a-select-option value="YARN_APPLICATION" >YARN APPLICATION</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="checkPoint配置" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flinkCheckpointConfig">
              <a-input v-model="model.flinkCheckpointConfig" placeholder="请输入checkPoint配置"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="checkPoint配置" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="jobType">
               {{model.jobType}}
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="任务描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="jobDesc">
              <a-textarea v-model="model.jobDesc" rows="4" placeholder="请输入任务描述" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="flink运行配置" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flinkRunConfig">
              <a-textarea v-model="model.flinkRunConfig" rows="4" placeholder="请输入flink运行配置" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="sql语句" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flinkSql">
              <codemirror ref="cm" :value="model.flinkSql" :options="cmOptions" class="fl-codemirror"  @input="onCodeChange"   />
              <a-button  @click="formatSQL()"  type="primary" style="margin-right: 20px;">SQL格式化</a-button>
              <a-button   type="primary" style="margin-bottom: 0;">SQL预检验</a-button>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <div class="sqlOperate" >

            </div>
          </a-col>

        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import { CodeMirror,codemirror } from 'vue-codemirror'
  import 'codemirror/lib/codemirror.css'
  // 引入主题后还需要在 options 中指定主题才会生效 darcula  gruvbox-dark hopscotch  monokai
  import 'codemirror/theme/panda-syntax.css'
  import 'codemirror/addon/hint/show-hint.css'
  import 'codemirror/addon/hint/show-hint'
  import 'codemirror/theme/mbo.css'
  import 'codemirror/mode/sql/sql.js'
  import 'codemirror/addon/hint/show-hint.js'
  import 'codemirror/addon/hint/sql-hint.js'
  import 'codemirror/addon/edit/matchbrackets.js'
  import 'codemirror/addon/selection/active-line'
  import 'codemirror/addon/selection/selection-pointer'
  import JCodeEditor from '@comp/jeecg/JCodeEditor.vue'
  import sqlFormatter from 'sql-formatter';


  export default {
    name: 'JobConfigForm',
    components: {
      codemirror
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    mounted() {
      this.$refs.cm.codemirror.on('keypress', (cm) => {
        cm.showHint()
      })
    },
    data () {
      return {

        model:{
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
           jobName: [
              { required: true, message: '请输入任务名称!'},
           ],
           deployMode: [
              { required: true, message: '请输入提交模式: standalone 、yarn 、yarn-session !'},
           ],
           jobDesc: [
              { required: true, message: '请输入flink运行配置!'},
           ],
           isOpen: [
              { required: true, message: '请输入1:开启 0: 关闭!'},
           ],
           status: [
              { required: true, message: '请输入1:运行中 0: 停止中 -1:运行失败!'},
           ],
        },
        url: {
          add: "/dcloud-flink-stream-platform/api/jobConfig/v1/add",
          edit: "/dcloud-flink-stream-platform/api/jobConfig/v1/edit",
          queryById: "/com.dcloud.streamweb.taskmanage/jobConfig/queryById"
        },
        cmOptions: {
          value: '',
          mode: 'text/x-mysql', // flink/x-fsql, text/x-mysql, text/x-sh
          theme: 'mbo', // solarized light,base16-light,cobalt,default,mbo,cobalt
          readOnly: false,
          tabSize: 4,
          line: true,
          lineNumbers: true,
          indentUnit: 4, // 缩进块用多少个空格表示 默认是2
          matchBrackets: true, // 括号匹配（这个需要导入codemirror的matchbrackets.js文件）
          extraKeys: { 'Ctrl': 'autocomplete' }, // 自定义快捷键
          hintOptions: { // 自定义提示选项
            completeSingle: false, // 当匹配只有一项的时候是否自动补全
            tables: {
              'table.dynamic-table-options.enabled': [],
              'table.sql-dialect': [],
              'table.local-time-zone': [],
              'table.generated-code.max-length': [],
              'table.exec': ['state.ttl', 'source.idle-timeout',
                'source.cdc-events-duplicate', 'window-agg.buffer-size-limit', 'source.cdc-events-duplicate',
                'mini-batch.enabled', 'mini-batch.allow-latency', 'mini-batch.enabled', 'mini-batch.allow-latency',
                'mini-batch.size', 'sink.not-null-enforcer', 'resource.default-parallelism', 'async-lookup.buffer-capacity',
                'async-lookup.timeout'],
              'table.optimizer': ['distinct-agg.split.enabled',
                'distinct-agg.split.bucket-num',
                'agg-phase-strategy',
                'reuse-sub-plan-enabled',
                'reuse-source-enabled',
                'source.predicate-pushdown-enabled',
                'join-reorder-enabled']
            }
          }
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      //currSelectedJobType  任务类型  case 0: SQl   1：Jar 2:SQL_BATCH
      add (currSelectedJobType) {
        this.modelDefault.jobType = currSelectedJobType
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.model = Object.assign({}, record);
        this.visible = true;
      },
      submitForm () {
        const that = this;
        console.log("this.model",this.model)
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
      onCodeChange(newValue) {
        this.model.flinkSql = newValue;
      },
      formatSQL(){

        // 使用sql-formatter格式化SQL代码
        const formattedSql = sqlFormatter.format(this.model.flinkSql);
        // 更新CodeMirror的值
        this.$refs.cm.codemirror.setValue(formattedSql);
      }
    }
  }
</script>
<style lang="less" scoped>
.fl-codemirror {
  border: 1px solid#C0C4CC;
  line-height: 20px;
}

.sqlOperate{
  display: flex; /* 使用Flex布局 */
  justify-content: flex-end; /* 子元素靠右对齐 */
}

</style>